package com.hong.taotaomall.service.filter;
import com.alibaba.fastjson.JSON;
import com.hong.taotaomall.common.BaseContext;
import com.hong.taotaomall.entity.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/*")
@Slf4j
public class loginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//        log.info("过滤器启动");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String RequestURI = request.getRequestURI();
        String []urls = {
                "/../../style/images/logo.png",
                "/pages/**",
                "/common/upload",
                "/common/download",
                "/category/list",
                "/user/sendMSG",
                "/user/login",
                "/district/**",
                "/goods/list",
                "/goods/detail/**",
                "/goods/like",
                "/goods/listById/*",
                "/goods/listById/",
                "/goods/listById/**",
                "/goods/page",
                "/user/login1",
                "/user/register",
                "/user/logout",
                "/shops/login",
                "/shops/logout",
                "/style/**",
                "/element-ui/**",
                "/js/**",

        };
        boolean check = check(RequestURI, urls);
        if (check) {
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getSession().getAttribute("shops") != null) {
            Long shops = (Long) request.getSession().getAttribute("shops");
            BaseContext.setCurentId(shops);
            filterChain.doFilter(request, response);
            return;
        }

        if (request.getSession().getAttribute("user") != null) {
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurentId(userId);
            filterChain.doFilter(request, response);
            return;
        }
        response.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));
        return;
    }

    private boolean check(String RequestURI, String[] urls) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, RequestURI);
            if (match) {
                 return true;
            }
        }
        return false;
    }
}
